<template>
  <view class="container">
    <!-- 评分概览 -->
    <view class="stats-card">
      <view class="stats-content">
        <view class="rating-left">
          <text class="score">{{ formatPrice(commentStats.rating) }}</text>
          <text class="score-label">综合评分</text>
        </view>
        <view class="rating-right">
          <wd-rate v-model="commentStats.rating" readonly size="16px" color="#eee" void-color="#ff4444" />
          <view class="rating-stats">
            <text class="good-rate">{{ commentStats.goodRatingPercentage }}% 好评</text>
            <text class="total">共{{ commentStats.total }}条评价</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 评论列表 -->
    <view class="comment-list">
      <view class="comment-item" v-for="comment in comments" :key="comment.id">
        <view class="user-info">
          <view class="info-left">
            <image 
              :src="comment.user.anonymous ? '/static/anonymous-avatar.png' : comment.user.avatar" 
              class="avatar"
            />
            <view class="user-meta">
              <text class="nickname">{{ comment.user.anonymous ? '匿名用户' : comment.user.nickname }}</text>
              <wd-rate v-model="comment.rating" readonly size="12px" color="#eee" void-color="#ff4444" />
            </view>
          </view>
          <text class="time">{{ formatTime(comment.createTime) }}</text>
        </view>

        <view class="comment-box">
          <view class="comment-content">
            <view class="content">{{ comment.content }}</view>
            
            <!-- 评论图片 -->
            <scroll-view 
              class="image-scroll" 
              scroll-x 
              v-if="comment.images && comment.images.length"
            >
              <view class="image-list">
                <image 
                  v-for="(img, index) in comment.images"
                  :key="index"
                  :src="img" 
                  mode="aspectFill"
                  @click="previewImage(comment.images, index)"
                  class="comment-image"
                />
              </view>
            </scroll-view>

            <!-- 商家回复 -->
            <view class="reply" v-if="comment.hasReply">
              <text class="reply-label">商家回复</text>
              <view class="reply-content">{{ comment.replyText }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="loading-wrap" v-if="loading">
      <wd-loading type="circle" />
      <text class="loading-text">加载中...</text>
    </view>
    <view class="no-more" v-if="!hasMore && !loading">没有更多评价了</view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { getProductComments } from '@/api/product'
import { formatPrice } from '@/utils/format'

// 评论统计数据
const commentStats = ref({
  total: 0,
  rating: 0,
  goodRatingPercentage: 0
})

// 评论列表数据
const comments = ref([])
const loading = ref(false)
const hasMore = ref(true)
const page = ref(1)
const pageSize = ref(10)
const productId = ref('')

// 获取评论列表
const getCommentList = async () => {
  if (!hasMore.value || loading.value) return
  
  loading.value = true
  try {
    const res = await getProductComments({
      id: productId.value,
      current: page.value,
      size: pageSize.value
    })
    
    // 首次加载时设置统计数据
    if (page.value === 1) {
      commentStats.value = {
        total: res.comments?.total || 0,
        rating: res.rating || 0,
        goodRatingPercentage: res.goodRatingPercentage || 0
      }
    }
    
    // 处理评论列表数据
    const newList = (res.comments?.records || []).map(item => ({
      id: item.id,
      user: {
        nickname: item.userNickname,
        avatar: item.avatarUrl || '/static/default-avatar.png',
        anonymous: item.anonymous
      },
      rating: Number(item.rating),
      content: item.reviewText,
      createTime: item.createTime,
      replyText: item.replyText,
      hasReply: item.reply === 1,
      images: item.images || []
    }))
    
    // 追加评论列表
    comments.value = page.value === 1 ? newList : [...comments.value, ...newList]
    
    // 更新分页
    page.value++
    hasMore.value = comments.value.length < (res.comments?.total || 0)
    
  } catch (error) {
    console.error('获取评论失败:', error)
    uni.showToast({
      title: '获取评论失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 页面加载
onLoad((options) => {
  console.log('评论页面参数:', options)
  if (options.productId) {
    productId.value = options.productId
    getCommentList()
  } else {
    uni.showToast({
      title: '商品ID不能为空',
      icon: 'none'
    })
  }
})

// 监听触底事件
onReachBottom(() => {
  getCommentList()
})

// 图片预览
const previewImage = (images, current) => {
  uni.previewImage({
    urls: images,
    current: images[current]
  })
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now - date
  
  // 24小时内显示"xx小时前"
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    return hours > 0 ? `${hours}小时前` : '刚刚'
  }
  
  // 7天内显示"x天前"
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    return `${days}天前`
  }
  
  // 超过7天显示具体日期
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 40rpx;
}

.stats-card {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

  .stats-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .rating-left {
      text-align: center;
      padding-right: 40rpx;
      border-right: 2rpx solid #eee;
      
      .score {
        font-size: 64rpx;
        font-weight: 600;
        color: #ff4444;
        line-height: 1;
        margin-bottom: 8rpx;
        display: block;
      }
      
      .score-label {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .rating-right {
      flex: 1;
      padding-left: 40rpx;
      
      .rating-stats {
        margin-top: 16rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        .good-rate {
          font-size: 26rpx;
          color: #ff4444;
          font-weight: 500;
        }
        
        .total {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
}

.comment-list {
  padding: 0 20rpx;
}

.comment-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.user-info {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 20rpx;
  
  .info-left {
    display: flex;
    align-items: center;
    
    .avatar {
      width: 72rpx;
      height: 72rpx;
      border-radius: 50%;
      margin-right: 16rpx;
      background: #f5f5f5;
      object-fit: cover;
    }
    
    .user-meta {
      display: flex;
      flex-direction: column;
      gap: 8rpx;
      
      .nickname {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }
    }
  }
  
  .time {
    font-size: 24rpx;
    color: #999;
  }
}

.comment-box {
  position: relative;
  left: 48rpx;
  background: #f8f8f8;
  border-radius: 12rpx;
  overflow: hidden;
  width: calc(100% - 48rpx);

  .comment-content {
    padding: 20rpx;
    
    .content {
      font-size: 28rpx;
      line-height: 1.6;
      color: #333;
      margin-bottom: 16rpx;
    }
  }
}

.image-scroll {
  width: 100%;
  white-space: nowrap;
  margin: 16rpx 0;
  
  .image-list {
    display: inline-flex;
    padding: 4rpx 0;
  }
  
  .comment-image {
    width: 160rpx;
    height: 160rpx;
    margin-right: 12rpx;
    border-radius: 8rpx;
    background: #f5f5f5;
  }
}

.reply {
  padding: 20rpx;
  background: #fff;
  border-radius: 8rpx;
  margin: 16rpx 0;
  
  .reply-label {
    font-size: 24rpx;
    color: #666;
    margin-bottom: 8rpx;
    display: block;
  }
  
  .reply-content {
    font-size: 26rpx;
    color: #333;
    line-height: 1.5;
  }
}

.loading-wrap {
  padding: 30rpx 0;
  text-align: center;
  
  .loading-text {
    font-size: 24rpx;
    color: #999;
    margin-top: 12rpx;
  }
}

.no-more {
  text-align: center;
  font-size: 24rpx;
  color: #999;
  padding: 40rpx 0;
}
</style> 